#include "mytcpserver.h"
#include "myhelper.h"
#include <QHostAddress>

myTcpServer::myTcpServer(databaseClass *db,QObject *parent) :
        QTcpServer(parent)
{
    tcpSocketMap = new QMap<QString,tcpInfo>;
    ClientSocketList= new QMap<int,myClientSocket *>;
    //this->setMaxPendingConnections(2000);
    this->mydb=db;
}

void myTcpServer::incomingConnection(int handle)
{
    //建立TCP—SOCKET
    myClientSocket *client=new myClientSocket(this->mydb,this,handle);
    client->setSocketDescriptor(handle);
    //QThread *thread=new QThread(client);
    //建立TCP槽函数
    connect(client,SIGNAL(ClientReadData(int,QString,int,QByteArray)),this,SLOT(ReadData(int,QString,int,QByteArray)));
    connect(client,SIGNAL(ClientDisConnect(int,QString,int)),this,SLOT(DisConnect(int,QString,int)));
    connect(client,SIGNAL(openClientDoorSend(QString)),this,SLOT(openDoorReadData(QString)));
    //client->moveToThread(thread);
    //connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    //thread->start();
    //发送新连接信息
    emit ClientConnect(handle, client->peerAddress().toString(),client->peerPort());
    //清理相同IP的TCP连接
    socketMap_Clear(client->peerAddress().toString());
    //链表中添加TCP连接
    ClientSocketList->insert(handle,client);
    qDebug()<<"incomingConnection"<<handle<<client->peerAddress().toString()<<"TCP连接数:"<<ClientSocketList->count()<<"\r\n";
}

void myTcpServer::ReadData(int clientID,QString IP,int Port,QByteArray data)
{
    emit ClientReadData(clientID,IP,Port,data);
    //qDebug()<<"ReadData"<<clientID<<IP<<Port<<QString(data);
    QStringList list;
    QString strSend;
    strSend=QString(data);
    if(strSend.indexOf(",")<0)
    {
        return;
    }
    list=strSend.split(',');
    if(list.count() > 2)
    {
        QString dev_Id,dev_flag,dev_number;
        dev_Id=list[0];//设备号
        dev_number=list[1];//设备类型号
        dev_flag=list[2];//标志
        //dev_byte=list[3];
        //TCP连接信息
        tcpInfo Info;
        Info.tcp_id=clientID;//进程号
        Info.tcp_ip=IP;//设备IP
        Info.tcp_port=Port;//设备Port
        //TCP连接检测
        if(dev_flag=="TIMER")
        {
            tcpSocketConnect(dev_Id,IP,Info);
        }
    }
}

void myTcpServer::openDoorReadData(QString data)
{
    emit openDoorSend(data);
}

void myTcpServer::DisConnect(int clientID,QString IP,int Port)
{
    if(ClientSocketList->contains(clientID))
    {
        ClientSocketList->remove(clientID);
        //socketMap_Link();
        //tcpMap_Link(clientID);
        emit ClientDisConnect(clientID,IP,Port);
        // th->exit();
        // delete th;
    }
}

//指定客户端连接发消息
void myTcpServer::SendData(int clientID,QByteArray data)
{
    if(ClientSocketList->contains(clientID))
    {
        QMap<int,myClientSocket *>::iterator itt=ClientSocketList->find(clientID);
        //qDebug()<<"SendData:"<<itt.key()<<data;
        itt.value()->write(data);
    }
}

void myTcpServer::tcpSocketConnect(QString dev_id,QString dev_ip,tcpInfo Info)
{
    if(tcpSocketMap->contains(dev_id))
    {
        QMap<QString,tcpInfo>::iterator tcpIt=tcpSocketMap->find(dev_id);
        if(tcpIt.value().tcp_ip==dev_ip )//&& tcpIt.value().tcp_port==dev_port)
        {
            if(ClientSocketList->contains(tcpIt.value().tcp_id))
            {
            return;
            }
        }
        //qDebug()<<"TCP连接新的设备"<<tcpIt.key()<<tcpIt.value().tcp_id<<tcpIt.value().tcp_ip<<tcpIt.value().tcp_port;
        if(ClientSocketList->contains(tcpIt.value().tcp_id))
        {
            QMap<int,myClientSocket *>::iterator itt=ClientSocketList->find(tcpIt.value().tcp_id);

            if( itt.value()->state()== QAbstractSocket::ConnectedState)
            {
                itt.value()->close();
            }
        }
        tcpSocketMap->remove(dev_id);
    }
    tcpSocketMap->insert(dev_id,Info);
    qDebug()<<"devinit"<<dev_id<<Info.tcp_id<<Info.tcp_ip<<Info.tcp_port;
    //tcpMap_Link(-1);
}

void myTcpServer::tcpSocketDisconnect(QString TcpID)
{
    if(tcpSocketMap->contains(TcpID))
    {
        //QMap<QString,tcpInfo>::iterator tcpIt=tcpSocketMap->find(TcpID);
        tcpSocketMap->remove(TcpID);
    }
}

void myTcpServer::OpenDoor(QString TcpID,QString flag,QString door,QString send_str)
{
    //qDebug()<<"myTcpServer:: OpenDoor 设备号检测:"<<tcpSocketMap->contains(TcpID);
    qDebug()<<"myTcpServer:: OpenDoor 设备号检测:"<<TcpID<<flag<<door;
    QString data;
    if(tcpSocketMap->contains(TcpID))
    {
        QMap<QString,tcpInfo>::iterator tcpIt=tcpSocketMap->find(TcpID);
        if(ClientSocketList->contains(tcpIt.value().tcp_id))
        {
            QMap<int,myClientSocket *>::iterator itt=ClientSocketList->find(tcpIt.value().tcp_id); 
            data=QString("%1,%2,%3,%4").arg(TcpID).arg(flag).arg("OPEN").arg(door);
            itt.value()->OpenDoorSlot(send_str);
            qDebug()<<"myTcpServer:: OpenDoor 发送数据:"<<tcpIt.value().tcp_id<<data;
        }else{
            data=QString("%1,%2,%3,%4").arg(TcpID).arg(flag).arg("OPEN").arg("ERROR");
            qDebug()<<"设备号TCP不存在";
            emit openDoorSend(data);
        }
    }else{
        data=QString("%1,%2,%3,%4").arg(TcpID).arg(flag).arg("OPEN").arg("ERROR");
        qDebug()<<"设备号不存在";
        emit openDoorSend(data);
    }
}

//void myTcpServer::tcpMap_Link(int uid)
//{
//    QMap<QString,tcpInfo>::iterator itt;
//    for ( itt = tcpSocketMap->begin(); itt != tcpSocketMap->end(); ++itt )
//    {
//        if(itt.value().tcp_id==uid)
//        {
//            tcpSocketMap->remove(itt.key());
//            break;
//        }
//    }
//    // qDebug()<<"==========设备数===========Begin"<<tcpSocketMap->count();
//    //for ( itt = tcpSocketMap->begin(); itt != tcpSocketMap->end(); ++itt )
//    // {
//    //     qDebug()<<" myTcpServer::tcpMap_Link"<<itt.key()<<itt.value().tcp_id<<itt.value().tcp_ip<<itt.value().tcp_port;
//    //  }
//    //  qDebug()<<"==========设备数===========End";
//}

//void myTcpServer::socketMap_Link()
//{
//    // qDebug()<<"=============TCP连接数============Start"<<ClientSocketList->count();
//    QMap<int,myClientSocket *>::iterator itt;
//    for ( itt = ClientSocketList->begin(); itt != ClientSocketList->end(); ++itt )
//    {
//        //qDebug()<<itt.key();
//    }
//    // qDebug()<<"=============TCP连接数============End";
//}


void myTcpServer::socketMap_Clear(QString ip)
{
    if(ClientSocketList->count()==0)
    {
        return;
    }
    QMap<int,myClientSocket *>::iterator itt;
    for ( itt = ClientSocketList->begin(); itt != ClientSocketList->end(); ++itt )
    {
        if(itt.value()->peerAddress().toString() == ip)
        {
            // qDebug()<<"相同IP清理myTcpServer::socketMap_Clear"<<itt.key()<<itt.value()->peerAddress().toString();
            if( itt.value()->state() == QAbstractSocket::ConnectedState)
            {
                itt.value()->close();
            }
            return;
        }
    }
}
